#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Project: spd-sxmcc
# squid_auth_helper.py
# Author: redice(qi@site-digger.com)
# Created at: 2016-10-12
# Python版本的Squid3.5权限认证脚本模板
# 在squid.conf中的"htcp_access deny all"之前加入如下配置：
# auth_param basic program /usr/bin/python /etc/conf/squid_auth_helper.py
# auth_param basic key_extras "%>a %la"
# auth_param basic realm IPRENT.CN Proxy Auth Required
# acl auth_users proxy_auth REQUIRED
# http_access allow auth_users
# 上面第二行的功能是将“客户端IP”和“服务端IP”作为命令行参数传递给认证脚本。支持更多宏格式http://devel.conf-cache.org/customlog/logformat.html
# key_extras是Squid3.5版本添加的新特性（老版本不支持），详见http://wiki.conf-cache.org/Squid-3.5
"""
@author: lyndon
@time Created on 2019/2/26 17:44
@desc
@example conf.conf:
auth_param basic program /usr/bin/python /etc/conf/squid_auth_helper.py
auth_param basic key_extras "%>a %la"
auth_param basic realm IPRENT.CN Proxy Auth Required
acl auth_users proxy_auth REQUIRED
http_access allow auth_users
"""

import sys
import logging

# 记录日志
# sudo chmod 755 /var/log/conf/squid_auth_helper.log
# sudo chown proxy:proxy /var/log/conf/squid_auth_helper.log
# logging.basicConfig(level=logging.DEBUG,
#                     format='%(asctime)s %(levelname)s %(message)s',
#                     filename='/var/log/conf/squid_auth_helper.log', filemode='a')
logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(levelname)s %(message)s',
                    filename=r'D:\iProject\myPython\com\teradata\squid\log\squid_auth_helper.log', filemode='a')


def matchpasswd(username, password, client_ip, local_ip):
    """检测是否有权限访问
    """
    # 这里仅实现了一个最简单的判断。你可以结合数据库实现复杂的认证逻辑。
    # 可以根据client_ip和local_ip做一些高级的限制，比如限制一个账号只能使用服务器上的某些IP（考虑多IP服务器情况）。
    if username == 'spdu' and password == 'JIqnEW218W9':
        logging.info('New auth request: username = {}, password = {}, client_ip = {}, local_ip = {}, {}'.format(username, password, client_ip, local_ip, 'OK'))
        return True
    logging.info('New auth request: username = {}, password = {}, client_ip = {}, local_ip = {}, {}'.format(username, password, client_ip, local_ip, 'ERR'))
    return False


if __name__ == '__main__':
    # while True:
        # 从stdin读取一行
        # line = sys.stdin.readline()
        # 提取username, password, client ip, local ip参数
        # username, password, client_ip, local_ip = line.split()
    username, password, client_ip, local_ip = ('spdu', 'JIqnEW218W9', '127.0.0.1', '127.0.0.1')
    # 判断是否有权限
    if matchpasswd(username, password, client_ip, local_ip):
        sys.stdout.write('OK\n')
    else:
        sys.stdout.write('ERR\n')
        # 输出
    # sys.stdout.flush()
